package net.javalib.flickr.search.activities;

import java.util.List;

import net.javalib.flickr.search.DownloadInfo;
import net.javalib.flickr.search.R;
import net.javalib.flickr.search.adapters.ImagesGridAdapter;
import net.javalib.flickr.search.flickr.FlickrImage;
import net.javalib.flickr.search.util.ViewWrapperHelper;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

/**
 * Application's main activity
 */
public class MainActivity extends AbstractBaseActivity {
	// UI References
	private EditText searchText;
	private ImageButton searchButton;
	private GridView searchGrid;
	private View searchProgress;
	private ProgressBar searchProgressBar;
	private TextView searchProgressText;
	// Adapters
	private ImagesGridAdapter adapter;
	
	// ----------------
	// LIFE CYCLE
	// ----------------
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        adapter = new ImagesGridAdapter(this);
        hookUI();
        adapter.setImages(app.getImages(),searchGrid);
    }
	
	@Override
	protected void onResume() {
		super.onResume();
        app.clearNotifications();
        adapter.refresh();
	}

	@Override
	protected void onPause() {
		super.onPause();
	}
	
	// ---------------
	// FUNCTIONALITY
	// ---------------
	
	/**
	 * Do a search if a search term exists
	 */
	private void doSearch() {
		String term = searchText.getText().toString().trim();
		if (!"".equals(term) && !app.isSearching) {
			adapter.clear();
			app.search(term);
			showKeyboard(false, searchText);
		}
	}
	
	// ---------------
	// CALLBACKS
	// ---------------
	
	@Override
	public void searchError(final Exception e) {
		runOnUiThread(new Runnable() {
			public void run() {
				AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
				builder.setMessage("Error: "+e.getMessage())
			       .setCancelable(false)
			       .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
			           public void onClick(DialogInterface dialog, int id) {
			                dialog.cancel();
			           }
			       });
				AlertDialog alert = builder.create();
				alert.show();
				searchDone();
			}
		});
	}
	
	/* (non-Javadoc)
	 * @see net.javalib.flickr.search.activities.AbstractBaseActivity#searchStarted(java.lang.String)
	 */
	@Override
	public void searchStarted(String term) {
		searchButton.setEnabled(false);
		searchText.setEnabled(false);
		searchProgress.setVisibility(View.VISIBLE);
		searchProgressText.setText("Searching, please wait");
	}

	/* (non-Javadoc)
	 * @see net.javalib.flickr.search.activities.AbstractBaseActivity#searchResult(java.util.List)
	 */
	@Override
	public void searchResult(final List<FlickrImage> images) {
		runOnUiThread(new Runnable() {
			public void run() {
		    	searchProgressBar.setMax(images.size());
		    	searchProgressText.setText("Please wait, downloading "+images.size()+" images");
				adapter.setImages(images,searchGrid);
			}
		});
	}
	
	/* (non-Javadoc)
	 * @see net.javalib.flickr.search.activities.AbstractBaseActivity#searchDone()
	 */
	@Override
	public void searchDone() {
		runOnUiThread(new Runnable() {
			public void run() {
				searchButton.setEnabled(true);
				searchText.setEnabled(true);
				searchProgress.setVisibility(View.GONE);
			}
		});
	}
	
	/* (non-Javadoc)
	 * @see net.javalib.flickr.search.activities.AbstractBaseActivity#bitmapDownloaded(net.javalib.flickr.search.DownloadInfo)
	 */
	@Override
	public void bitmapDownloaded(final DownloadInfo request) {
		runOnUiThread(new Runnable() {
			public void run() {
				// Update progress
				searchProgressBar.setProgress(app.getProgress());
				searchProgressText.setText("Please wait, "+app.getProgress()+" / "+app.getImages().size()+" images downloaded.");

				View view = adapter.getView(request.image);
				if (view != null) {
					ViewWrapperHelper wrapper = (ViewWrapperHelper) view.getTag();
					wrapper.refresh();
//					if (!request.isThumbnail) {
//						ProgressBar progress = (ProgressBar) wrapper.getView(R.id.thumbnail_progress);
//						progress.setVisibility(View.INVISIBLE);
//					}
				}
			}
		});
	}
	
	
	/* (non-Javadoc)
	 * @see net.javalib.flickr.search.activities.AbstractBaseActivity#onProgress(net.javalib.flickr.search.flickr.FlickrImage, int)
	 */
	@Override
	public void onProgress(FlickrImage image, int percentage) {
		View view = adapter.getView(image);
		if (view != null) {
			ViewWrapperHelper wrapper = (ViewWrapperHelper) view.getTag();
			ProgressBar progress = (ProgressBar) wrapper.getView(R.id.thumbnail_progress);
			progress.setProgress(percentage);
		}		
	}
	
    private void hookUI() {
    	searchText = (EditText) findViewById(R.id.search_text);
    	searchButton = (ImageButton) findViewById(R.id.search_button);
    	searchGrid = (GridView) findViewById(R.id.search_grid);
    	searchProgress = (View) findViewById(R.id.search_progress);
    	searchProgressBar = (ProgressBar) findViewById(R.id.search_progress_bar);
    	searchProgressText = (TextView) findViewById(R.id.search_progress_text);

    	searchButton.setEnabled(!app.isSearching);
    	searchText.setEnabled(!app.isSearching);
    	if (app.isSearching)
    		searchProgress.setVisibility(View.VISIBLE);
    	else
    		searchProgress.setVisibility(View.GONE);
    	
    	searchGrid.setAdapter(adapter);
        searchGrid.setOnItemClickListener(new OnItemClickListener() {
	        	@Override
	        	public void onItemClick(AdapterView<?> arg0, View view, int arg2, long arg3) {
	        		ViewWrapperHelper wrapper = (ViewWrapperHelper) view.getTag();
	        		FlickrImage image = (FlickrImage) wrapper.tag;
	        		if (image.downloaded) {
	        			startActivity(DetailsActivity.createIntent(MainActivity.this, image));
	        		}
	        	}
	        });
        
    	searchButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				doSearch();
			}
		});
    	
    	searchText.setOnKeyListener(new OnKeyListener() {
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER) {
					doSearch();
					return true;
				}
				return false;
			}
		});
    }
    
}